package com.youxin.logcenter.service.impl;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.youxin.busfoundation.bean.BaseLogModel;
import com.youxin.busfoundation.bean.ResponseObject;
import com.youxin.busfoundation.config.KafkaConfig;
import com.youxin.busfoundation.enums.OsType;
import com.youxin.busfoundation.enums.SystemType;
import com.youxin.foundation.db.utils.KeyGenerationUtils;
import com.youxin.foundation.utils.JsonUtils;
import com.youxin.foundation.utils.StringUtils;
import com.youxin.logcenter.bean.RequestQueryLog;
import com.youxin.logcenter.dao.LogcpMapper;
import com.youxin.logcenter.dao.LogoaMapper;
import com.youxin.logcenter.dao.LogpcMapper;
import com.youxin.logcenter.kafka.KafkaProducerLog;
import com.youxin.logcenter.model.Logcp;
import com.youxin.logcenter.model.Logoa;
import com.youxin.logcenter.model.Logpc;
import com.youxin.logcenter.service.LogApiService;

@Service("logApiService")
public class LogApiServiceImpl implements LogApiService{

	private static final String LOCALIP="0:0:0:0:0:0:0:1";
	@Autowired
	private LogpcMapper logpcMapper;
	
	@Autowired
	private LogoaMapper logoaMapper;
	
	@Autowired
	private LogcpMapper logcpMapper;
	/**
	 * 保存日志并发送到Kafka
	 * @param request  HttpServletRequest
	 * @param logBean BaseLogModel
	 * @param systemType SystemType
	 * @return ResponseObject 返回结果
	 * @throws UnknownHostException 不能识别的主机异常
	 */
	public ResponseObject saveLog(HttpServletRequest request,BaseLogModel logBean,SystemType systemType) throws UnknownHostException
	{
		String forwardedIp = request.getHeader("X-FORWARDED-FOR");
		String ipAddress = request.getRemoteAddr();
		ipAddress = request.getRemoteAddr();
		if (LOCALIP.equals(ipAddress)) {
			InetAddress localip = InetAddress.getLocalHost();
			ipAddress = localip.getHostAddress();				
		}
		if(ipAddress==null)
		{
			ipAddress="";
		}			
		long id = KeyGenerationUtils.generateKey();
		logBean.setId(id);
		logBean.setCreateTime(new Date());
		logBean.setTraceId(id);
		logBean.setSerialId(1L);
		logBean.setIp(ipAddress);
		//logBean.setUrl(request.getRequestURL().toString());
		if(forwardedIp!=null){
			logBean.setForwardedIp(forwardedIp);
		}
        String  browserDetails  =   request.getHeader("User-Agent");
        OsType osType=getOsType(browserDetails);
        browserDetails=StringUtils.substring(browserDetails, 1000);
        logBean.setDeviceInfo(browserDetails);
        logBean.setDeviceType(osType.getValue());
		String jsonString=JsonUtils.objectToFasterxmlJsonString(logBean);
		String result=new KafkaProducerLog().sendMessage(systemType.getName(),jsonString, KafkaConfig.getConfig());
		if(StringUtils.isNullOrEmpty(result)){
			return ResponseObject.successObject();
		}
		return ResponseObject.systemError(result);
	}
	
	@SuppressWarnings("unchecked")
	public   ResponseObject queryLog(RequestQueryLog logBean)
	{	
		if(logBean.getSystemType()==SystemType.OA.getValue())
		{
			List<Logoa> list=logoaMapper.select(logBean);	
			logBean.setResults((List<BaseLogModel>)(List<?>)list);
			return new ResponseObject(logBean);
		}
		if(logBean.getSystemType()==SystemType.CP.getValue())
		{
			List<Logcp> list=logcpMapper.select(logBean);	
			logBean.setResults((List<BaseLogModel>)(List<?>)list);
			return new ResponseObject(logBean);
		}
		
		List<Logpc> list=logpcMapper.select(logBean);	
		logBean.setResults((List<BaseLogModel>)(List<?>)list);
		return new ResponseObject(logBean);
	}
	
	/**
	 * 获取操作系统类型
	 * @param browserDetails
	 * @return
	 */
	private static OsType getOsType(String  browserDetails)
	{
		if(browserDetails==null)
		{
			return OsType.Unknown;
		}
        String  userAgent =   browserDetails.toLowerCase();
        if(userAgent.indexOf("windows")>=0||userAgent.indexOf("mac")>=0||userAgent.indexOf("x11")>=0)
        {
        	return OsType.PC;
        }

        if(userAgent.indexOf("iphone")>=0||userAgent.indexOf("ipad")>=0)
        {
        	return OsType.IOS;
        }
        
        if(userAgent.indexOf("android")>=0)
        {
        	return OsType.Android;
        }
        return OsType.Unknown;
	}

}
